<script setup>
import { newRandomUid } from "@/utils";
import Color from "../setting/Color.vue";
import PrizePopupSelect from "../setting/PrizePopupSelect.vue";

const props = defineProps({
  config: {
    type: Object,
    required: true,
  },
  name: {
    type: String,
    default: "",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  group: {
    type: Array,
    default: () => [],
  },
});

const emits = defineEmits(["update:config", "change"]);

const form = ref({
  $position: { top: 0, left: 13 },
  $size: { width: 345 },
  $positionType: "relative",
  $removeable: true,
  theme: "#3277FE",
});

const formRef = ref();

const detail = computed({
  get: () => {
    return Object.assign({}, form.value, props.config);
  },
  set: (val) => {
    emits("update:config", val);
    emits("change", val);
  },
});

const initConfig = () => {
  if (!detail.value.$pageFlag) {
    detail.value.$pageFlag = `WeekSign-${newRandomUid()}`;
    onChange();
  }
};

const onChange = (val) => {
  detail.value = detail.value;
};

// 表单校验
const check = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid, invalidFields) => {
      if (valid) {
        resolve();
      } else {
        reject(
          `${props.name}校验未通过，${
            invalidFields[Object.keys(invalidFields)[0]][0].message
          }`
        );
      }
    });
  });
};

onMounted(() => {
  nextTick(() => {
    initConfig();
    onChange();
  });
});

defineExpose({ check });
</script>
<template>
  <el-form
    ref="formRef"
    :model="detail"
    :disabled="disabled"
    label-width="auto"
  >
    <PrizePopupSelect v-model="detail" :group="group" @change="onChange" />
    <Color v-model="detail.theme" name="主题色" @change="onChange" />
  </el-form>
</template>
